import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/product_stockorder_odoo_api.dart';
import 'package:flutter_admin/models/odoo/product_stockorder.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/pages/odoo/product_productunitprice/product_list.dart';
import 'package:multi_select_flutter/dialog/multi_select_dialog_field.dart';
import 'package:multi_select_flutter/util/multi_select_item.dart';
import 'package:multi_select_flutter/util/multi_select_list_type.dart';
import '../../../generated/l10n.dart';

class ProductStockorderSupplementEdit extends StatefulWidget {
  ProductStockorderSupplementEdit({this.productStockorder});

  final ProductStockorder? productStockorder;

  @override
  _ProductStockorderSupplementEditState createState() =>
      _ProductStockorderSupplementEditState();
}

class _ProductStockorderSupplementEditState
    extends State<ProductStockorderSupplementEdit> {
  late ProductStockorder productStockorder;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  List<MultiSelectItem<Object?>> processList = [];
  Map processMap = {};
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.productStockorder == null;
    this.productStockorder = widget.productStockorder ?? ProductStockorder();
    // _selectedAnimals5 = _animals;
    _loadSelectVO();
  }

  _loadSelectVO() async {
    ResponseBodyApi responseBodyApi =
        await DynamicDataApi.getModels(model: "mrp.routing.workcenter");
    if (responseBodyApi.success!) {
      for (Map map in responseBodyApi.data) {
        processMap[map['note']] = map['id'];
        processList.add(MultiSelectItem<dynamic>(map["id"], map['name']));
      }
    }
    if (isAdd!) {
      var res = await ProductStockorderOdooApi.getOrder();
      if (res.success!) {
        productStockorder.stockorderno = res.data;
      }
    }
    setState(() {});
  }

  _selectProduct() async {
    formKey.currentState!.save();
    this.isLoading = false;
    setState(() {});
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ProductList(),
      ),
    ).then((v) async {
      if (v != null) {
        //_query();
        productStockorder.productId = v['id'].toString();
        productStockorder.productCode =
            v['default_code'] != false ? v['default_code'] : '';
        productStockorder.productName = v['name'] != false ? v['name'] : '';
        productStockorder.productDesc =
            v['description'] != false ? v['description'] : '';
        productStockorder.processList = [];
        // var res = await HttpUtil.get("http://10.1.13.100/mesapi/ztkd/CommonData/GetFlowInfo?PartCodes=['${productStockorder.productCode}']");
        var res = await HttpUtil.get(
            "/MES/mesapi/ztkd/CommonData/GetFlowInfo?PartCodes=['${productStockorder.productCode}']");
        // var url = "/MES/mesapi/ztkd/CommonData/GetFlowInfo?PartCodes=['${productStockorder.productCode}']";
        // Dio _dio = Dio();
        // _dio.options.method = "GET";
        // Response res = await _dio.request(url);
        if (res.success! && res.data.length != 0) {
          var data = res.data[0]["FlowOper"];
          for (var i = 0; i < data.length; i++) {
            if (processMap.containsKey(data[i]['OperId'])) {
              productStockorder.processList!.add(processMap[data[i]['OperId']]);
            }
          }
        }
      }
      this.isLoading = true;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '补单单号',
            enable: false,
            value: productStockorder.stockorderno,
            onSaved: (v) {
              productStockorder.stockorderno = v;
            },
          ),
          CrySelectDate(
            context,
            label: '补单日期',
            value: productStockorder.orderdate,
            onSaved: (v) {
              productStockorder.orderdate = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            label: '零件名称',
            value: productStockorder.productName,
            onTap: () => {_selectProduct()},
            onSaved: (v) {
              productStockorder.productName = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            label: '零件图号',
            enable: false,
            value: productStockorder.productCode,
          ),
          CryInput(
            label: '规格型号',
            enable: false,
            value: productStockorder.productDesc,
          ),
          CryInputNum(
            label: '补单数量',
            value: productStockorder.orderqty,
            onSaved: (v) {
              productStockorder.orderqty = v;
            },
            validator: (v) {
              return double.parse(v!) == 0 ? "补单数量不能为0" : null;
            },
          ),
          isLoading
              ? Padding(
                  padding: EdgeInsets.all(20),
                  child: MultiSelectDialogField(
                    items: processList,
                    title: Text("工序"),
                    listType: MultiSelectListType.LIST,
                    searchable: true,
                    searchHint: "查找",
                    confirmText: Text("确定"),
                    cancelText: Text("取消"),
                    buttonIcon: Icon(
                      Icons.search,
                      // color: Colors.blue,
                    ),
                    buttonText: Text(
                      "选择工序",
                      style: TextStyle(
                        // color: Colors.blue[800],
                        fontSize: 16,
                      ),
                    ),
                    initialValue: productStockorder.processList,
                    onConfirm: (results) {
                      productStockorder.processList = results;
                    },
                    // chipDisplay: MultiSelectChipDisplay(
                    //   // chipColor: Colors.black12,
                    //   onTap: (value) {
                    //     setState(() {
                    //       productStockorder.processList!.remove(value);
                    //     });
                    //   },
                    // ), // setting the value of this in initState() to pre-select values.
                  ),
                )
              : Container(),
          CryInput(
            label: '备注',
            value: productStockorder.remark,
            onSaved: (v) {
              productStockorder.remark = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            if (productStockorder.processList == null ||
                productStockorder.processList!.length == 0) {
              CryUtils.message("请选择工序");
              return;
            }
            form.save();
            productStockorder.isSupplement = '1';
            ProductStockorderOdooApi.saveOrUpdate(productStockorder.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                //package:flutter_admin/pages/common/cry(re s.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
